﻿using DDD.Core.CQRS;
using DDD.Core.Exceptions.Bussines.User;
using DDD.Core.Result;
using DDD.Domain.Abstract.UnitOfWork;
using DDD.Domain.Repositories;

namespace DDD.Application.Commands.UserCommand.DeleteUserById
{
    internal class DeleteUserByIdCommandHandler : ICommandHandler<DeleteUserByIdCommand, ApiResult<bool>, bool>
    {
        private readonly IUserRepository _userRepository;
        private readonly IUnitOfWork _unitOfWork;

        public DeleteUserByIdCommandHandler(IUserRepository userRepository, IUnitOfWork unitOfWork)
        {
            _userRepository = userRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<ApiResult<bool>> Handle(DeleteUserByIdCommand request, CancellationToken cancellationToken)
        {
            var user = _userRepository.Get(request.Id);
            if (user == null)
                throw new NotFoundUserByUserIdException(request.Id);

            _userRepository.Delete(user);
            var result = await _unitOfWork.SaveChanegeAsync() > 0;

            return ApiResult<bool>.Success(result);
        }
    }
}
